package com.cedarhd.finance.msg.domain.service;

import com.cedarhd.finance.msg.common.utils.PicUtil;
import com.cedarhd.finance.msg.common.utils.StringHelper;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lipei
 * @date 2018/3/7
 */
@Service
public class PictureService {

    private Logger logger = LoggerFactory.getLogger(PictureService.class);

    @Value("${qn.accessKey}")
    private String accessKey;


    @Value("${qn.secretKey}")
    private String secretKey;


    public  Boolean  uploadFile(MultipartFile file, String fileName){

        String localFilePath = PicUtil.saveFile(file);

        if(StringHelper.isEmpty(localFilePath)){
            return false;
        }

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //要上传的空间
        String bucket = "picture";

        //上传到七牛后保存的文件名---不指定的话，七牛随机产生-无后缀
        String key = fileName;

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            logger.info("putRet.key = {}", putRet.key);
            logger.info("putRet.hash = {}", putRet.hash);
            return true;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return false;
        }
    }

}
